<?php

namespace addons\third\model;

use think\Model;
use app\common\library\Exception;

/**
 * 第三方登录模型
 */
class Third extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [];

    const PLATFORM_WECHAT   = 'wechat';
    const PLATFORM_WEIBO    = 'weibo';
    const PLATFORM_QQ       = 'qq';
    const PLATFORM_WEMINI   = 'wemini';


    /**
     * 创建一条Third数据
     * 
     * @param string    $platform   平台
     * @param int       $userID     用户ID
     * @param string    $mobile     手机号码
     * @param array     $wechatData 微信信息
     * @param int       $time       当前时间
     * @return array
     */
    public function createThird($platform, $userID, $mobile, $wechatData, $time = 0)
    {
        if (empty($platform) || empty($userID) || empty($wechatData)) {
            new Exception('Params error');
        }

        $time = !empty($time) ? $time : time();

        $thirdInsertData = [
            'platform'      => $platform,
            'openid'        => $wechatData['openid'],
            'logintime'     => $time,
            'access_token'  => isset($wechatData['access_token']['access_token']) ? $wechatData['access_token']['access_token'] : '',
            'refresh_token' => isset($wechatData['refresh_token']) ? $wechatData['refresh_token'] : '',
            'expires_in'    => isset($wechatData['expires_in']) ? $wechatData['expires_in'] : '',
            'expiretime'    => isset($wechatData['expires_in']) ? $time + $wechatData['expires_in'] : '',
            'user_id'       => $userID,
            'mobile'        => $mobile,
            'openname'      => isset($wechatData['userinfo']['nickname']) ? $wechatData['userinfo']['nickname'] : '',
            'country_code'  => ''
        ];
        $thirdInsertData = self::create($thirdInsertData);

        return $thirdInsertData;
    }
}
